package main

import (
	"flag"
	"fmt"
	"os"
	"strings"

	"code/config"
	"code/generator"

	"gopkg.in/yaml.v2"
)

func main() {
	// 定义命令行参数

	name := flag.String("name", "", "模块名称")
	tag := flag.String("tag", "", "标签")
	typeArg := flag.String("type", "", "类型 (LIST/ADD/UPDATE/DEL/CONTENT)")
	table := flag.String("table", "", "数据库表名")
	api := flag.String("api", "", "接口路径")
	apiType := flag.String("apitype", "", "接口提交类型 (GET/POST/PUT)")
	action := flag.String("action", "", "动作类型 (ADD/DELETE)")
	codeType := flag.String("codeType", "interface", "可选类型: interface 或 dto")

	// 解析命令行参数
	flag.Parse()

	// 检查必需的命令行参数
	if *name == "" {
		fmt.Println("模块名称不能为空")
		return
	}
	generator.ValidateName(name)
	generator.ValidateName(action)
	//默认提交方式处理
	if *apiType == "" {
		apiTypeLowCase := strings.ToLower(*typeArg)
		switch apiTypeLowCase {
		case "list", "content", "del":
			*apiType = "GET"
		case "add", "update":
			*apiType = "POST"
			if *typeArg == "update" {
				*apiType = "PUT"
			}
		default:
			//fmt.Println("接口提交类型不能为空")
			return
		}
		//fmt.Println("类型不能为空")
		//return
	}
	fmt.Printf("提交类型: %s\n", *apiType)
	if *table == "" {
		fmt.Println("表名不能为空")
		return
	}
	if *api == "" {
		fmt.Println("接口路径不能为空")
		return
	}
	if *apiType == "" {
		fmt.Println("接口提交类型不能为空")
		return
	}
	if *action == "" {
		fmt.Println("动作类型不能为空")
		return
	}

	if *codeType == "" {
		fmt.Println("代码类型不能为空")
		return
	}

	// 读取 YAML 配置文件（如果需要）
	configFile, err := os.Open("config.yaml")
	if err != nil {
		fmt.Println("无法打开配置文件:", err)
		return
	}
	defer configFile.Close()

	var config config.Config
	decoder := yaml.NewDecoder(configFile)
	if err := decoder.Decode(&config); err != nil {
		fmt.Println("无法解析配置文件:", err)
		return
	}

	// 将命令行参数赋值给 config

	config.Name = *name
	config.Tag = *tag
	config.Type = *typeArg
	config.Table = *table
	config.Api = *api
	config.ApiType = *apiType
	config.Action = *action
	config.CodeType = *codeType
	// 打印配置内容
	//fmt.Printf("Config: %+v\n", config)
	// 调用生成代码的函数
	generator.GenerateFiles(config)
}
